import React from 'react'
import styles from './index.module.css'
import {Tag, Toast, Stepper} from 'antd-mobile'
import bgImg from '../../assets/golive/pic_dt.png'
import Nav from '../../components/nav'
import food2 from '../../assets/products/food2.jpg'
import {withRouter} from 'react-router-dom'
import QueueAnim from 'rc-queue-anim';
import {connect} from "react-redux";
import request from "../../utils/request";

const Spec = ({skuTagList, productDetail, skuInfo, buyNum, stepperChange, onSelect, onEnsure, selectedSku}) => {
    return (
        <QueueAnim type={"bottom"}>
            <div className={styles.spec} key={1}>
                <img src={food2} alt="" style={{
                    width: '100px',
                    position: 'absolute',
                    top: '-10px',
                    left: '10px'
                }}/>
                <div style={{marginLeft: '120px'}}>
                    <h3>{productDetail.title}</h3>
                    <b>¥{skuInfo.price || ''}</b>
                    <span style={{marginLeft: '6px'}}>库存 {skuInfo.stock || ''}</span>
                </div>
                <div style={{
                    marginTop: '30px'
                }}/>
                {
                    skuTagList.map((item, inx) => {
                        let {AttributeList} = item;
                        return (
                            <div key={inx}>
                                <div style={{margin: '6px 0 6px 6px',}}>{item.title}</div>
                                <div className={styles.property}>
                                    {
                                        AttributeList ? AttributeList.map((attr, key) => {
                                            return (<Tag style={{marginLeft: '6px'}} key={key} onChange={(selected) => {
                                                onSelect(selected, attr);
                                            }} selected={selectedSku[item.id] === attr.id}>{attr.title}</Tag>)
                                        }) : ''
                                    }
                                </div>
                            </div>
                        );
                    })
                }
                <div className={styles.buy}>
                    <span style={{color: 'gray'}}>购买数量</span>
                    <Stepper
                        showNumber
                        style={{width: '120px', marginRight: '10px'}}
                        max={10} min={1}
                        value={buyNum}
                        onChange={stepperChange}
                    />
                </div>

                <div style={{
                    padding: '5px 10px',
                    borderTop: '1px solid #F4F4F4'
                }}>
                    <button
                        style={{
                            width: '100%',
                            border: 'none',
                            padding: '10px 5px',
                        }}
                        onClick={() => {
                            onEnsure();
                        }}>确定
                    </button>
                </div>
            </div>
        </QueueAnim>
    );
};

class Index extends React.Component {

    state = {
        toggleStatus: false,
        isCollect: false,
        productDetail: {},
        skuTagList: [],
        skuInfo: {},
        btnType: '',
        buyNum: 1,
        selectedSku: []
    };

    stepperChange = (value) => {
        this.setState({
            buyNum: value
        });
    };
    onEnsure = () => {
        const {btnType, skuInfo, buyNum} = this.state;
        const {history, match: {params: {productId}}, dispatch} = this.props;
        if (btnType === 'addCart') {
            this.addCart().then(() => {
                Toast.success('添加成功，在购物车等亲~');
            });
            this.toggleSpec('')
        }
        if (btnType === 'buyNow') {
            dispatch({
                type: 'place-order',
                payload: [
                    {productId: parseInt(productId), skuId: skuInfo.id, num: buyNum}
                ],
            });
            history.push(`/order/ensure`);
        }
    };
    //添加购物车
    addCart = async () => {
        const {skuTagList, buyNum, skuInfo} = this.state;
        let selectItems = [];
        skuTagList.forEach((tags) => {
            tags.AttributeList.forEach((attr) => {
                attr.selected && selectItems.push(attr)
            });
        });
        await request('/product/add-cart', {
            method: 'POST',
            data: {
                productSkuId: skuInfo.id,
                num: buyNum
            },
        });
    };
    //价格计算
    computePrice = async (selectItems) => {
        let attrIdsStr = '';
        Object.keys(selectItems).forEach((key) => {
            attrIdsStr += `&attrIds=${selectItems[key]}`;
        });
        const {match: {params: {productId}}} = this.props;
        const response = await request(`/product/sku/compute-price?productId=${productId}${attrIdsStr}`)
        return response.data;
    };

    onSelect = (selected, attr) => {
        const {skuTagList, selectedSku} = this.state;
        let {SkuTagId} = attr;
        const newSelectedSku = {...selectedSku};
        skuTagList.forEach((item) => {
            if (SkuTagId === item.id) {
                if (selected) {
                    newSelectedSku[item.id] = attr.id;
                } else {
                    delete (newSelectedSku[item.id])
                }
            }
        });

        if (skuTagList.length === Object.keys(newSelectedSku).length) {
            this.computePrice(newSelectedSku).then((result) => {
                const {skuDetail} = result;
                const skuInfo = {
                    id: parseInt(skuDetail.id),
                    price: skuDetail.price,
                    stock: skuDetail.stock
                };
                this.setState({skuInfo});
            });
        }
        this.setState({selectedSku: newSelectedSku});
    };

    toggleSpec = (btnType) => {
        this.setState((state) => ({
            toggleStatus: !state.toggleStatus,
            btnType
        }));
    };
    toggleCollect = () => {
        const {match: {params: {productId}}} = this.props;
        request(`/product/user-collect?productId=${productId}&isCollect=${!this.state.isCollect}`).then(() => {
            this.setState((state) => ({
                isCollect: !state.isCollect
            }));
        }).catch(() => {
            Toast.fail('请求失败')
        });
    };

    componentDidMount() {
        const {match: {params: {productId}}} = this.props;
        request(`/product/detail/${productId}`).then((result) => {
            const {data: {isCollect, productDetail, skuTagList}} = result;
            const newProductDetail = {
                title: productDetail.name,
                id: productDetail.id,
                price: productDetail.price,
                sales: productDetail.sales,
                totalStock: productDetail.totalStock
            };
            const skuInfo = {
                price: productDetail.price,
                stock: productDetail.totalStock,
            };
            const newSkuTagList = skuTagList.map((item, inx) => {
                return {
                    ...item,
                    AttributeList: item.AttributeList.map((val) => {
                        return {...val, selected: false}
                    })
                }
            });

            this.setState({
                isCollect: isCollect >= 1,
                productDetail: newProductDetail,
                skuTagList: newSkuTagList,
                selectedSkuAttributes: {},
                skuInfo
            })
        }).catch(() => {
            Toast.fail('请求失败')
        });
    }

    render() {

        const {history, dispatch, product} = this.props;
        const {productDetail, skuTagList, skuInfo, buyNum, selectedSku} = this.state;
        return (
            <div className={styles.container}>
                {this.state.toggleStatus && <div className={styles.shadow} onClick={() => {
                    this.toggleSpec('');
                }}/>}
                <div className={styles.main}>
                    <Nav onLeftClick={() => {
                        history.goBack();
                    }}/>
                    <img src={bgImg} alt="" className={styles.bgImg}/>
                    <div className={styles.content}>
                        <div className={styles.summary}>
                            <div className={styles.goodsTitle}>
                                {productDetail.title || ''}
                            </div>
                            <div className={styles.priceSale}>
                                <b style={{
                                    fontSize: '16px'
                                }}>¥{productDetail.price || ''}</b>
                                <span>已售{productDetail.sales || ''}</span>
                            </div>
                        </div>
                        <br/>
                        <div className={styles.middle}>
                            <div style={{
                                paddingBottom: '8px',
                                display: 'flex',
                                justifyContent: 'space-between'
                            }}>
                                <span>运费</span>
                                <span>¥10</span>
                            </div>
                            <div style={{
                                paddingTop: '8px',
                                borderTop: '1px solid #F9F9F9',
                                display: 'flex',
                                justifyContent: 'space-between'
                            }}>
                                <span>已选</span>
                                <span>茶具完整；一套</span>
                            </div>
                        </div>
                        <div className={styles.detail}>
                            <div className={styles.detailTitle}>
                                图文详情
                            </div>
                        </div>
                    </div>
                </div>

                {this.state.toggleStatus &&
                <Spec
                    skuTagList={skuTagList}
                    productDetail={productDetail}
                    skuInfo={skuInfo}
                    onSelect={this.onSelect}
                    onEnsure={this.onEnsure}
                    buyNum={buyNum}
                    stepperChange={this.stepperChange}
                    selectedSku={selectedSku}
                />}
                <div className={styles.bottom}>
                    <div style={{
                        textAlign: 'center',
                        width: '56px',
                        borderRight: '1px solid #F4F4F4',
                        boxSizing: 'border-box'
                    }} onClick={this.toggleCollect}>
                        <i className={this.state.isCollect ? "iconfont icon-heart-fill" : "iconfont icon-heart"}
                           style={{
                               fontSize: '30px',
                               position: 'relative',
                           }}/>
                        <div style={{fontSize: '10px'}}>收藏</div>
                    </div>
                    <div style={{
                        textAlign: 'center',
                        width: '60px',
                        borderRight: '1px solid #F4F4F4',
                        boxSizing: 'border-box'
                    }} onClick={() => {
                        dispatch({
                            type: 'change-tab',
                            callback: () => {
                                history.push('/index')
                            }
                        });
                    }}>
                        <i className={"iconfont icon-carryout"} style={{
                            fontSize: '30px',
                        }}/>
                        <div style={{fontSize: '10px'}}>购物车</div>
                    </div>


                    <button style={{
                        border: 'none',
                        backgroundColor: '#EBEBF3',
                        color: 'black',
                        height: '100%',
                        fontSize: '16px',
                        padding: '0 15px',
                        flex: 1,
                    }} onClick={() => {
                        this.toggleSpec('addCart');
                    }}>加入购物车
                    </button>

                    <button style={{
                        border: 'none',
                        backgroundColor: '#302F34',
                        color: 'white',
                        height: '100%',
                        fontSize: '16px',
                        padding: '0 15px',
                        flex: 1,
                    }} onClick={() => {
                        this.toggleSpec('buyNow');
                    }}>立即购买
                    </button>

                </div>
            </div>

        );
    }
}

const mapDispatchToProps = (dispatch) => { // 默认传递参数就是dispatch
    return {
        dispatch
    };
};
export default connect((state) => ({
    order: state.order,
    product: state.product,
}), mapDispatchToProps)(withRouter(Index))
